<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>H5 + base64</title>
  </head>
  <body>
    <h2>HTML Forms</h2>
    <div>
      <label for="file">file:</label> <br />
      <input type="file" id="file" name="file" /><br /><br />
      <input type="submit" value="Submit" onclick="submit()" />
    </div>

    <script>
      let upload = {};
      function submit() {
        console.log("here", upload);
        fetch("/submitb64", {
          method: "POST",
          body: JSON.stringify(upload), // base64转json放body上传
          headers: {
            // content-type上传文件时，不可能用application/x-www-form-urlencoded(有等号，base64也有等号)
            "Content-Type": "application/json",
          },
        });
      }
      document.getElementById("file").addEventListener("change", (e) => {
        const files = e.target.files; // 获取文件列表
        console.log(files);
        for (let file of files) {
          const fr = new FileReader(); // 使用base64 调用FileReader
          fr.readAsDataURL(file);
          fr.onload = () => {
            console.log(fr, "fr");
            // fr.result  文件生成的base64结果， 前22个字符是类型描述说明，需要切割出来
            upload.data = fr.result.substr(22);
            upload.name = file.name;
          };
        }
      });
    </script>
  </body>
</html>
